package samples.bankleitzahlen;


import org.dom4j.Element;
import org.dom4j.XPathException;

import br.cin.ufpe.in1118.middleware.distribution.message.SOAPFactory;
import br.cin.ufpe.in1118.middleware.distribution.message.SOAPFaultException;
import br.cin.ufpe.in1118.middleware.distribution.services.util.MiddlewareUtil;
import br.cin.ufpe.in1118.middleware.exceptions.RemoteException;

public final class Bankleitzahlen_SF extends SOAPFactory {

	@Override
	public Object fromSOAP(String operation, String soapMessage) throws RemoteException {
		Element rootElement = null;
		try {
			rootElement = createRootElement(soapMessage);

			Element response = (Element) rootElement.selectSingleNode("//ns1:details");

			if (response != null) {
				Bank bank = new Bank();
				bank.setBezeichnung(response.element("bezeichnung").getText());
				bank.setBic(response.element("bic").getText());
				bank.setOrt(response.element("ort").getText());
				bank.setPlz(response.element("plz").getText());
				return bank;
			}
		} catch (XPathException e) {
			Element elem = (Element) rootElement.selectSingleNode("//faultstring");
			throw new RemoteException(new SOAPFaultException(elem.getText()));
		} catch (Exception e) {
			MiddlewareUtil.encapsulateException(e);
		}
		return null;
	}

	@Override
	public String toSOAP(String operation, Object... parameters) {
		String str = "<getBank xmlns=\"http://thomas-bayer.com/blz/\"><blz>%s</blz></getBank>";
		String body = String.format(str, parameters[0]);
		return String.format("%s\n%s\n%s\n%s\n%s\n%s\n",
				TEMPLATE_XML_DECLARATION,
				TEMPLATE_HEADER_ENV,
				TEMPLATE_HEADER_BODY,
				body,
				TEMPLATE_TAIL_BODY,
				TEMPLATE_TAIL_ENV);
	}

}
